Module# 04: Arrays                                                             Lecture#13: Class ArrayList for Arrays

 

// Example 13.1: Creating a simple collection

 

/* The following program illustrate the use of the simple constructor to declare a collection. */

     

import java.util.ArrayList;

public class SimpleArrayListExample {

    public static void main(String[] args)      {

      // Creating an ArrayList of String

      ArrayList<String> animals = new ArrayList<String>();     

      // Adding new elements to the ArrayList

      animals.add("Lion");

      animals.add("Tiger");

      animals.add("Cat");

      animals.add("Dog");

      // animals.add(2019);  Is it valid?

      // This shows how an entire collection can be displayed

      System.out.println(animals);     

    }

}

 

// Example 13.2: Creating an ArrayList object with an existing collection

 

// Creating an ArrayList from another collection using the ArrayList(Collection c) constructor.

import java.util.*;

public class CreateArrayListFromCollectionExample {

    public static void main(String[] args)      {

      // Creating a collection first. Let it be with the simple method

          ArrayList<Integer> aList = new ArrayList<Integer>(); //Declaring aList as a collection

      aList.add(2); // Adding elements into the aList collection

      aList.add(3);

      aList.add(5);

      aList.add(7);

      aList.add(11);

      // Creating another collection initially with aList collection

      ArrayList<Integer> numbers = new ArrayList<Integer>(aList);

      numbers.add(13); // Add two more numbers into the numbers collection

      numbers.add(17);

      System.out.println(aList); // Now, yu have two collections: aList and numbers.

      System.out.println(numbers); // Printing the two collections

        }

}

 

 

// Example 13.3: Creating an ArrayList object with user defined objects

 

/* This program illustrates the creation of an ArrayList collection of user defined type. */

     

public class Person {

    private String name;

    private int age;

    public Person(String name, int age)   {

        this.name = name;

        this.age = age;

    }

    public void printData() {

        System.out.println(name + " " + age);

    }

}

 

import java.util.ArrayList;

 

public class ArrayListUserDefinedObjectDemo{

   public static void main(String[] args) {

    // Declaring pList as a collection of type Person of capacity 5

    ArrayList<Person> pList = new ArrayList<Person>(5);  

    pList.add(new Person("Ram", 25));

    Person p2 = new Person("Sita", 22);   // Create a new object

    pList.add(p2);                        // add the object

    pList.add(new Person("John", 34));

    pList.add(p2);                        // Duplicate entry is allowed

    pList.add(new Person("Rahim", 29));   // Five objects are added

    pList.add(new Person("Lilly", 24));

    // No issue to accommodate, list grows dynamically

    pList.forEach(p -> p.printData());         

    // An way to access each object in a class

  }

}

 

// Example 13.4: Insertion into an ArrayList collection

 

// This program illustrates the insertion operation into an ArrayList collection.

import java.util.ArrayList;

public class InsertionArrayListDemo {

     public static void main(String[] args)     {

      // Creating a collection first. Let it be with the simple method

      ArrayList<Integer> odd = new ArrayList<>();  // Declaring aList as a collection

      // Adding elements into the odd collection

      odd.add(1);

      odd.add(3);

      odd.add(5);

      odd.add(7);

      odd.add(9);

      System.out.println(odd);

 

      // Creating another collection, say number with elements from odd collection

     

ArrayList<Integer> numbers = new ArrayList<Integer>(odd);

      System.out.println(numbers);    // same as odd       

     

      // Creating another collection, say even1 

      ArrayList<Integer> even1 = new ArrayList<Integer>();

      // Add numbers into the even1 collection

      even1.add(2);

      even1.add(4);

      even1.add(6);

     

      // Insert all the elements of even1 collection at the end of number collection

      numbers.addAll(even1);

      System.out.println(numbers);

     

      // Creating another collection, say any 

      ArrayList<Integer> any = new ArrayList<Integer>();

      // Add numbers into “any” collection

      any.add(8);

      any.add(11);

      any.add(13);

                 

      // Add the collection any at 5-th location of the collection numbers

      numbers.addAll(5, any);

      //add an object at a specific location of the colletion numbers

      numbers.add(0,0);

      System.out.println(numbers);

      // What will happen to the following?

      //numbers.add(100,999);  ??    

     }

}

 

// Example 13.5: Accessing objects in an ArrayList collection

 

import java.util.ArrayList;

public class AccessingArrayListObjects{

     public static void main(String[] args)     {

     ArrayList<String> topCompanies = new ArrayList<String>();

     // Check if an ArrayList is empty

     System.out.println("Is the topCompanies list empty? :  " + topCompanies.isEmpty());

     topCompanies.add("Google");

     topCompanies.add("Apple");

     topCompanies.add("Microsoft");

     topCompanies.add("Amazon");

             topCompanies.add("Facebook");

         

      // Find the size of an ArrayList

      System.out.println("Here are the top " + topCompanies.size() + “Companies in the world");

      System.out.println(topCompanies);   // Print the companies names

      // Retrieve the element at a given index

      String bestCompany = topCompanies.get(0);

      System.out.println("Best Company: " + bestCompany);

      String secondBestCompany = topCompanies.get(1);

      System.out.println("Second Best Company: " + secondBestCompany);

      String lastCompany = topCompanies.get(topCompanies.size() - 1);

      System.out.println("Last Company in the list: " + lastCompany);

      // Modify the element at a given index

      topCompanies.set(4, "Walmart");

      System.out.println("Modified top companies list: " + topCompanies);

     }

}

 

// Example 13.6: Deletion from an ArrayList collection

 

import java.util.ArrayList;

import java.util.function.Predicate;

 

public class DeletionArrayListDemo {

    public static void main(String[] args) {

      // Create a collection. Initially empty

          ArrayList<String> langs = new ArrayList<String>(); 

        

      // Add elements into the collection

      langs.add("C");

      langs.add("C++");

      langs.add("Java");

      langs.add("Python");

      langs.add("R");

      langs.add("Spark");

      System.out.println("Initial List: " + langs);

     

      // Removing elements from the collection

      langs.remove(5);  // Remove the element at index `5`

      System.out.println("After remove(5): " + langs);

      // Remove the first occurrence of the given element from the ArrayList

      boolean status = langs.remove("Smalltalk");

      System.out.println("Smalltalk is removed : " + status);

      // Remove all the elements that exist in a given collection

      ArrayList<String> script = new ArrayList<String>();

      script.add("SQL");

      script.add("Python");

      script.add("Javascript");

      langs.removeAll(script);    // Remove intersection of langs and script

      System.out.println("After script removal: " + langs);

     

      // Remove all the elements that satisfy the given predicate

      langs.removeIf(new Predicate<String>() {@Override

          public boolean test(String s) {

               return s.startsWith("C");});

     

      /* The above removeIf() call can also be written using lambda expression like this :

      langs.removeIf(s -> s.startsWith("C"));

      */

      System.out.println("After Removing all elements that start with \"C\": " + langs);

      // Remove all elements from the ArrayList

      langs.clear();

      System.out.println("List is empty? " + langs.isEmpty());

     }

}

 

// Example 13.7: Searching an ArrayList collection

 

import java.util.ArrayList;

 

public class SearchElementsInArrayListExample   {

     public static void main(String[] args)     {

      ArrayList<String> names = new ArrayList<String>();

      names.add("John");

      names.add("Alice");

      names.add("Bob");

      names.add("Steve");

      names.add("John");

      names.add("Steve");

      names.add("Maria");

      // Check if an ArrayList contains a given element

      System.out.println("Bob exist? : " + names.contains("Bob"));

      // Find the index of the first occurrence of an element in an ArrayList

      System.out.println("indexOf \"Steve\": " + names.indexOf("Steve"));

      System.out.println("indexOf \"Mark\": " + names.indexOf("Mark"));

      // Find the index of the last occurrence of an element in an ArrayList

      System.out.println("lastIndexOf John : " + names.lastIndexOf("John"));

      System.out.println("lastIndexOf Bill: " + names.lastIndexOf("Bill"));

     }

}

 

// Example 13.8: Sorting an ArrayList collection

 

import java.util.ArrayList;

import java.util.Collections;

import java.util.List;

 

public class ArrayListCollectionsSortExample {

    public static void main(String[] args) {

        List<Integer> numbers = new ArrayList<Integer>();

        numbers.add(13);

        numbers.add(7);

        numbers.add(18);

        numbers.add(5);

        numbers.add(2);

 

        System.out.println("Before : " + numbers);

 

        // Sorting an ArrayList using Collections.sort() method

        Collections.sort(numbers);

 

        System.out.println("After : " + numbers);

    }

}

 

// Example 13.9: Sorting an ArrayList collection

 

import java.util.*;

 

public class ArrayListSortExample {

    public static void main(String[] args) {

        List<String> names = new ArrayList<>();

        names.add("Lisa");

        names.add("Preeti");

        names.add("Jay");

        names.add("Soma");

 

        System.out.println("Names : " + names);

 

        // Sort an ArrayList using its sort() method.

        // You must pass a Comparator to the ArrayList.sort() method.

        names.sort(new Comparator<String>() {

            @Override

            public int compare(String name1, String name2) {

                return name1.compareTo(name2);

            }

        });

        System.out.println("Sorted Names : " + names);

    }

}

 

// Example 13.10: Sorting an ArrayList collection

 

import java.util.*;

 

class Person {

    private String name;

    private Integer age;

 

    public Person(String name, Integer age){

        this.name = name;

        this.age = age;

    }

    public String getName() {

        return name;

    }

    public void setName(String name) {

        this.name = name;

    }

 

public Integer getAge() {

        return age;

    }

    public void setAge(Integer age) {

        this.age = age;

    }

    @Override

    public String toString() {

        return "{" +

                "name='" + name + '\'' +

                ", age=" + age +

                '}';

    }

}

 

public class ArrayListObjectSortExample {

    public static void main(String[] args) {

        List<Person> people = new ArrayList<>();

        people.add(new Person("Sachin", 47));

        people.add(new Person("Chris", 34));

        people.add(new Person("Rajeev", 25));

        people.add(new Person("David", 31));

 

        System.out.println("Person List : " + people);

 

        // Sort People by their Age

        people.sort((person1, person2) -> {

            return person1.getAge() - person2.getAge();

        });

 

        // A more concise way of writing the above sorting function

        people.sort(Comparator.comparingInt(Person::getAge));

 

        System.out.println("Sorted Person List by Age : " + people);

 

        // Sort using Collections.sort() method by passing the custom Comparator

        Collections.sort(people, Comparator.comparing(Person::getName));

        System.out.println("Sorted Person List by Name : " + people);

    }

}

 

// Example 13.11: Traversing an ArrayList collection

 

import java.util.ArrayList;

import java.util.Iterator;

import java.util.ListIterator;

 

public class IterateOverArrayListDemo {

     public static void main(String[] args)     {

      ArrayList<String> tvShows = new ArrayList<String>();

      tvShows.add("Nimki Mukhiya");

      tvShows.add("Game of Thrones");

      tvShows.add("Mahabharat");

      tvShows.add("Balika Badhu");

      System.out.println("Traversing using forEach()  and lambda \n");

      tvShows.forEach(tvShow -> { System.out.println(tvShow); });

     

      System.out.println("\n=== Iterate using an iterator() ===");     

      Iterator<String> tvShowIterator = tvShows.iterator();

      while (tvShowIterator.hasNext()) {

           String tvShow = tvShowIterator.next();

           System.out.println(tvShow);

      }

     

      System.out.println("Traversing usingiterator() and forEachRemaining()");

      tvShowIterator = tvShows.iterator();

      tvShowIterator.forEachRemaining(tvShow -> {

            System.out.println(tvShow);

            });

     

      System.out.println("Traversing using a listIterator() \n");

      // Here, we start from the end of the list and traverse backwards.

      ListIterator<String> tvShowListIterator = tvShows.listIterator(tvShows.size());

      while (tvShowListIterator.hasPrevious()){

          String tvShow = tvShowListIterator.previous();

          System.out.println(tvShow);

      }

      System.out.println("\n=== Iterate using simple for-each loop ===");

      for(String tvShow: tvShows)   {

          System.out.println(tvShow);

      }

     

      System.out.println("\n=== Iterate using for loop with index ===");

      for(int i = 0; i < tvShows.size(); i++){

          System.out.println(tvShows.get(i));

      }

     }

}

 

// Example 13.12: Traversing an ArrayList collection

 

import java.util.*;

public class ArrayListIteratorRemoveExample {

    public static void main(String[] args) {

      List<Integer> numbers = new ArrayList<Integer>();

      numbers.add(13);

      numbers.add(18);

      numbers.add(25);

      numbers.add(40);

      Iterator<Integer> numbersIterator = numbers.iterator();

      while (numbersIterator.hasNext()) {

           Integer num = numbersIterator.next();

           if(num % 2 != 0) {

            numbersIterator.remove();

           }

      }

      System.out.println(numbers);

    }

}

 

// Example 13.13: Bulk copy of an ArrayList collection

 

import java.util.*;

class ArrayListToArray {

    public static void main(String args[])      {

      // Create an array list.

     ArrayList<Integer> al = new ArrayList<Integer>();

      // Add elements to the array list.

      al.add(1);

      al.add(2);

      al.add(3);

      al.add(4);

      System.out.println("Contents of al: " + al);

      // Get the array.

      Integer ia[] = new Integer[al.size()];

      ia = al.toArray(ia);

      // Object[] ia = al.toArray();   Alternatively

      int sum = 0;

      // Sum the array.

      for(int i : ia)

         sum += i;

         System.out.println("Sum is: " + sum);

      }

  }